package im.composer.vapu.rmi.codec.bzip2;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import org.itadaki.bzip2.BZip2OutputStream;
import org.tritonus.share.sampled.FloatSampleBuffer;

import im.composer.vapu.rmi.TimedFloatSampleBuffer;
import im.composer.vapu.rmi.codec.FloatSampleEncoder;

public class BZIP2FloatSampleEncoder implements FloatSampleEncoder {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6101873615896043042L;

	@Override
	public byte[] encode(TimedFloatSampleBuffer buf) throws IOException {
		int size = getSizeInBytes(buf.getBuffer());
		ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
		int block_size = (int)Math.ceil(size/100000d);
		if(block_size>9){
			block_size = 9;
		}else if(block_size<1){
			block_size = 1;
		}
		BZip2OutputStream gos = new BZip2OutputStream(baos,block_size);
		ObjectOutputStream oos = new ObjectOutputStream(gos);
		oos.writeObject(buf);
		oos.flush();
		oos.close();
		gos.flush();
		gos.close();
		return baos.toByteArray();
	}
	
	private int getSizeInBytes(FloatSampleBuffer buf){
		return buf.getChannelCount() * buf.getSampleCount() * 4;
	}

}
